#include "../include/sql.hpp"
int sql_connect(MYSQL **conn)
{
    string server = "localhost";
    string user = "xzq";
    string passward = "Xzq20031003zshxf.";
    string db = "disk";
    unsigned int port = 3306;
    *conn = mysql_init(nullptr);
    if (!mysql_real_connect(*conn, server.c_str(), user.c_str(), passward.c_str(), db.c_str(), port, nullptr, 0))
    {
        exit(0);
    }
    else
    {
        printf("connect successful! \n");
    }
    mysql_set_character_set(*conn, "utf8");
    return 0;
}
int find_name(MYSQL *conn, char *name, char *salt)
{
    MYSQL_RES *res;
    MYSQL_ROW row;
    char query[300] = "select salt from user where username='";
    sprintf(query, "%s%s%s", query, name, "'");
    puts(query);
    int t, ret = -1;
    t = mysql_query(conn, query);
    if (t)
    {
        printf("Error making query:%s\n", mysql_error(conn));
    }
    else
    {
        res = mysql_use_result(conn);
        if (res)
        {
            if ((row = mysql_fetch_row(res)) != nullptr)
            {
                if (*row[0] == 0)
                {
                    ret = -1;
                }
                else
                {
                    if (salt)
                    {
                        strcpy(salt, row[0]);
                    }
                    ret = 0;
                }
            }
        }
        else
        {
            printf("查询出错\n");
            exit(0);
        }
        mysql_free_result(res);
    }
    return ret;
}
void get_salt(char *str)
{
    str[0] = '$';
    str[1] = '5';
    str[2] = '$';
    int i = 0, flag = 0;
    for (i = 3; i < STR_LEN - 1; i++)
    {
        flag = rand() % 3;
        switch (flag)
        {
        case 0:
            str[i] = rand() % 26 + 'a';
            break;
        case 1:
            str[i] = rand() % 26 + 'A';
            break;
        case 2:
            str[i] = rand() % 10 + '0';
            break;
        }
    }
    str[STR_LEN - 1] = '\0';
    return;
}
void add_user(MYSQL *conn, char *name, char *salt, char *mima)
{
    char query[300] = "insert into user (username,salt,cryptpasswd) values(";
    sprintf(query, "%s'%s','%s','%s')", query, name, salt, mima);
    puts(query);
    int t = mysql_query(conn, query);
    if (t)
    {
        printf("Error making query:%s\n", mysql_error(conn));
    }
    else
    {
        printf("insert success\n");
    }
}
int math_user(MYSQL *conn, char *name, char *password, char *token)
{
    MYSQL_RES *res;
    MYSQL_ROW row;
    char query[300] = "select cryptpasswd from user where username='";
    sprintf(query, "%s%s%s", query, name, "'");
    puts(query);
    int t = 0, ret = -1;
    t = mysql_query(conn, query);
    if (t)
    {
        printf("Error making query:%s\n", mysql_error(conn));
    }
    else
    {
        res = mysql_use_result(conn);
        if (res)
        {
            if ((row = mysql_fetch_row(res)) != nullptr)
            {
                if (*row[0] == 0)
                {
                    ret = -1;
                }
                else if (strcmp(row[0], password) != 0)
                {
                    ret = -1;
                }
                else
                {
                    ret = 0;
                    mysql_free_result(res);
                    char pquery[300] = "update user set token='";
                    strcpy(query, "where username ='");
                    sprintf(pquery, "%s%s' %s%s'", pquery, token, query, name);
                    puts(pquery);
                    t = mysql_query(conn, pquery);
                    if (t)
                    {
                        printf("Error making query:%s\n", mysql_error(conn));
                    }
                    else
                    {
                        printf("update success\n");
                    }
                    return ret;
                }
            }
        }
        else
        {
            printf("查询出错\n");
            exit(0);
        }
        mysql_free_result(res);
    }
    return ret;
}
int math_token(MYSQL *conn, char *name, char *token)
{
    MYSQL_RES *res;
    MYSQL_ROW row;
    char query[300] = "select token from user where username='";
    sprintf(query, "%s%s%s", query, name, "'");
    puts(query);
    int t = 0, ret = -1;
    t = mysql_query(conn, query);
    if (t)
    {
        printf("Error making query:%s\n", mysql_error(conn));
    }
    else
    {
        res = mysql_use_result(conn);
        if (res)
        {
            if ((row = mysql_fetch_row(res)) != nullptr)
            {
                if (*row[0] == 0)
                {
                    ret = -1;
                }
                else if (strcmp(row[0], token) == 0)
                {
                    ret = 0;
                }
            }
        }
        else
        {
            printf("查询出错\n");
            exit(0);
        }
        mysql_free_result(res);
    }
    return ret;
}
void ls_func(MYSQL *conn, char *name, int code, char *buf)
{
    MYSQL_RES *res;
    MYSQL_ROW row;
    *buf = 0;
    char query[300] = "select filetype,filename,filesize from Directory where belongID=";
    sprintf(query, "%s'%s' and procode=%d", query, name, code);
    puts(query);
    int t = mysql_query(conn, query);
    if (t)
    {
        printf("Error making query:%s\n", mysql_error(conn));
    }
    else
    {
        res = mysql_use_result(conn);
        if (res)
        {
            while ((row = mysql_fetch_row(res)) != nullptr)
            {
                sprintf(buf, "%s-%-10s%-20s %10s B\n", buf, row[0], row[1], row[2]);
            }
        }
        else
        {
            printf("Don't find data\n");
        }
        mysql_free_result(res);
    }
    return;
}
// 返回当前code（pcode）下的上级目录的code，并把当前目录名保存到path中，失败-1；
int find_pre_code(MYSQL *conn, char *path, int pcode)
{
    MYSQL_RES *res;
    MYSQL_ROW row;
    char query[300] = "select procode,filename from Directory where code=";
    sprintf(query, "%s%d", query, pcode);
    puts(query);
    int ret = -1;
    int t = mysql_query(conn, query);
    if (t)
    {
        printf("Error making query:%s\n", mysql_error(conn));
    }
    else
    {
        res = mysql_use_result(conn);
        if (res)
        {
            if ((row = mysql_fetch_row(res)) != nullptr)
            {
                strcpy(path, row[1]);
                ret = atoi(row[0]);
            }
        }
        else
        {
            printf("查询出错\n");
            exit(0);
        }
        mysql_free_result(res);
    }
    return ret;
}
// 返回code下一级filename的code值（只能是文件夹）
int find_later_code(MYSQL *conn, int cur_code, char *filename, char *name)
{
    MYSQL_RES *res;
    MYSQL_ROW row;
    char query[300] = "select code from Directory where procode=";
    sprintf(query, "%s%d and belongID='%s' and filetype='d' and filename='%s'", query, cur_code, name, filename);
    puts(query);
    int ret = -1;
    int t = mysql_query(conn, query);
    if (t)
    {
        printf("Error making query:%s\n", mysql_error(conn));
    }
    else
    {
        res = mysql_use_result(conn);
        if (res)
        {
            if ((row = mysql_fetch_row(res)) != nullptr)
            {
                ret = atoi(row[0]);
            }
        }
        else
        {
            printf("查询出错\n");
            exit(0);
        }
        mysql_free_result(res);
    }
    return ret;
}
int cd_func(MYSQL *conn, Train_t *ptrain, QUR_msg *pqq_msg, char *name, int *pcode)
{
    char tranbuf[200];
    MYSQL_RES *res;
    MYSQL_ROW row;
    // 定位cd.....后自己所处于哪个目录下
    if (strcmp(pqq_msg->buf1, "..") == 0)
    {
        if (*pcode == 0)
        {
            return -1;
        }
        char query[300] = "select procode from Directory where code=";
        sprintf(query, "%s%d and belongID='%s'", query, *pcode, name);
        puts(query);
        int t = mysql_query(conn, query);
        if (t)
        {
            printf("Error making query:%s\n", mysql_error(conn));
        }
        else
        {
            res = mysql_use_result(conn);
            if (res)
            {
                if ((row = mysql_fetch_row(res)) != nullptr)
                {
                    *pcode = atoi(row[0]);
                }
                else
                {
                    mysql_free_result(res);
                    return -1;
                }
            }
            else
            {
                printf("查询出错\n");
                exit(0);
            }
            mysql_free_result(res);
        }
    }
    else if (*pqq_msg->buf1 == '/')
    {
        int ret, code = 0;
        char *pcur, *pre;
        pcur = pre = pqq_msg->buf1 + 1;
        while (*pcur != 0)
        {
            while (*pcur != '/' && pcur != 0)
                pcur++;
            if (*pcur != 0)
            {
                *pcur = 0;
                pcur++;
            }
            if (*pre != 0)
            {
                ret = find_later_code(conn, code, pre, name);
                if (ret == -1)
                {
                    return -1;
                }
                code = ret;
                pre = pcur;
            }
        }
        *pcode = code;
    }
    else
    {
        int ret = find_later_code(conn, *pcode, pqq_msg->buf1, name);
        if (ret == -1)
        {
            return -1;
        }
        *pcode = ret;
    }
}
int operate_func(MYSQL *conn, Train_t *ptrain, QUR_msg *pqq_msg, char *name, int *pcode)
{
    MYSQL_RES *res;
    MYSQL_ROW row;
    if (strcmp(pqq_msg->buf, "mkdir") == 0)
    {
        char pquery[300] = "select * from Directory where procode=";
        sprintf(pquery, "%s%d and filename='%s' and belongID='%s'", pquery, *pcode, pqq_msg->buf1, name);
        puts(pquery);
        int t = mysql_query(conn, pquery);
        if (t)
        {
            printf("Error making query:%s\n", mysql_error(conn));
        }
        else
        {
            res = mysql_use_result(conn);
            if (res)
            {
                if ((row = mysql_fetch_row(res)) != nullptr)
                {
                    mysql_free_result(res);
                    return -1;
                }
                else
                {
                    mysql_free_result(res);
                    char query[300] = "insert into Directory (procode,filename,belongID,filetype) values(";
                    sprintf(query, "%s%d,'%s','%s','%s')", query, *pcode, pqq_msg->buf1, name, "d");
                    puts(query);
                    int t = mysql_query(conn, query);
                    if (t)
                    {
                        printf("Error making query:%s\n", mysql_error(conn));
                    }
                    else
                    {
                        printf("insert success\n");
                    }
                    ptrain->len = 0;
                    ptrain->ctl_code = OPERATE_OK;
                    return 0;
                }
            }
            else
            {
                printf("查询出错\n");
                exit(0);
            }
        }
    }
    else if (strcmp(pqq_msg->buf, "cd") == 0)
    {
        int ret = cd_func(conn, ptrain, pqq_msg, name, pcode);
        if (ret == -1)
            return -1;
        else
            return 0;
    }
    else if (strcmp(pqq_msg->buf, "rm") == 0)
    {
    }
    ptrain->len = 0;
    ptrain->ctl_code = OPERATE_NO;
    return -1;
}
void Llog(MYSQL *conn, const char *action, const char *name, const char *ip, const char *result)
{
    char query[500] = "insert into Login (action,name,ip_port,result) values ";
    sprintf(query, "%s('%s','%s','%s','%s')", query, action, name, ip, result);
    puts(query);
    int t = mysql_query(conn, query);
    if (t)
    {
        printf("Error making query:%s\n", mysql_error(conn));
    }
    else
    {
        printf("insert success\n");
    }
}
void Olog(MYSQL *conn, const char *name, const char *handle, const char *object, const char *result)
{
    char query[500] = "insert into Operate (name,handle,object,result) values ";
    sprintf(query, "%s('%s','%s','%s','%s')", query, name, handle, object, result);
    puts(query);
    int t = mysql_query(conn, query);
    if (t)
    {
        printf("Error making query:%s\n", mysql_error(conn));
    }
    else
    {
        printf("insert success\n");
    }
}